<template>
  <div>
    <div class="info">
      <div class="title">
        <span>编辑个人资料</span>
      </div>
      <hr/>
      <div class="personal">
        <el-form :validate-on-rule-change="false" :model="registerForm" ref="registerForm" label-width="70px" class="demo-ruleForm" :rules="rules">
          <el-form-item prop="username" label="用户名">
            <el-input v-model="registerForm.username" placeholder="用户名"></el-input>
          </el-form-item>
          <el-form-item prop="sex" label="性别">
            <el-radio-group v-model="registerForm.sex">
              <el-radio :label="0">女</el-radio>
              <el-radio :label="1">男</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item prop="avator" label="用户头像" size="mini">
            <el-upload action="#"
                       :http-request="upload"
                       accept="image/jpeg,image/jpg,image/png"
                       :before-upload="beforeUpload"
            >
              <el-button size="mini" >上传用户头像</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item prop="phoneNum" label="手机">
            <el-input v-model="registerForm.phoneNum" placeholder="手机"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="registerForm.email" placeholder="邮箱"></el-input>
          </el-form-item>
          <el-form-item prop="birth" label="生日">
            <el-date-picker type='date' :editable="false" v-model="registerForm.birth" placeholder="选择日期" style="width: 100%;"></el-date-picker>
          </el-form-item>
          <el-form-item prop="introduction" label="签名">
            <el-input v-model="registerForm.introduction" placeholder="签名"></el-input>
          </el-form-item>
          <el-form-item prop="location" label="地区">
            <el-select v-model="registerForm.location" placeholder="地区" style="width: 100%;">
              <el-option v-for=" item in cities" :key="item.value" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="btn">
          <div @click="saveMsg">保存</div>
        </div>
      </div>

    </div>
  </div>

</template>

<script>
import {mapState} from 'vuex'
import {rules,cities} from "@/assets/data/form";
import COS from "cos-js-sdk-v5";
export default {
  name: "Info",
  data() {
    return {
      registerForm: {
        username: '',       //用户名
        sex: '',            //性别
        phoneNum: '',       //手机
        email: '',          //邮箱
        birth: '',          //生日
        introduction: '',   //签名
        location: '',       //地区
        avator: ''
      },
      cities: [],            //所有的地区--省
      rules: {}             //表单提交的规则
    }
  },
  mounted() {
    this.getUser()
    this.cities = cities
    this.rules = rules
    this.$store.dispatch('showTencent')
  },
  methods: {
    async getUser() {
      let result = await this.$API.reqShowConsumerFromId(this.userId)
      if (result.code == 10000) {
        this.registerForm.username = result.data.username;
        this.registerForm.sex = result.data.sex;
        this.registerForm.phoneNum = result.data.phoneNum;
        this.registerForm.email = result.data.email;
        this.registerForm.birth = result.data.birth.substr(0, 10);
        this.registerForm.introduction = result.data.introduction;
        this.registerForm.location = result.data.location;
        this.registerForm.avator = result.data.avator;
      } else {
        await Promise.reject(new Error('fail'))
      }
    },
    async saveMsg() {
      let d = new Date(this.registerForm.birth);
      let datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
      let params = new URLSearchParams();
      params.append('id', this.userId);
      params.append('userName', this.registerForm.username);
      params.append('sex', this.registerForm.sex);
      params.append('phoneNum', this.registerForm.phoneNum);
      params.append('email', this.registerForm.email);
      params.append('birth', datetime);
      params.append('introduction', this.registerForm.introduction);
      params.append('location', this.registerForm.location);
      params.append('avator', this.registerForm.avator);
      let result = await this.$API.reqUpdateConsumerInfo(params)
      if (result.code==10000){
        this.$notify.success('更新个人信息成功')
      }else {
        this.$notify.error('系统繁忙')
      }
    },
    //更新前校验图片
    beforeUpload(file) {
      const isJPG = (file.type === 'image/jpeg') || (file.type === 'image/png')
      if (!isJPG) {
        this.$notify.error('只支持上传 jpg / png  格式的图片')
        return false
      }
      const isLt2M = (file.size / 1024 / 1024) < 2
      if (!isLt2M) {
        this.$notify.error('上传图片大于2M')
        return false
      }
      return true
    },
    //添加图片
    upload(res) {
      const cos = new COS({
        SecretId: this.SecretId, // 身份识别ID
        SecretKey: this.SecretKey // 身份秘钥
      })
      if (res.file) {
        //上传图片
        cos.putObject({
          Bucket: this.Bucket, /* 存储桶 */
          Region: this.Region, /* 存储桶所在地域，必须字段 */
          Key: this.Key + '/img/consumerPic/' + res.file.name, /* 文件名 */
          StorageClass: this.StorageClass, // 上传模式, 标准模式
          Body: res.file // 上传文件对象
        }, async (err, data) => {
          // 上传成功之后
          if (data.statusCode === 200) {
            this.registerForm.avator = 'https://' + data.Location
          }
        })
      }
    }
  },
    computed: {
      ...mapState({
        userId: state => state.home.userId,
        SecretId:state => state.register.SecretId,
        SecretKey:state => state.register.SecretKey,
        Bucket:state => state.register.Bucket,
        Region:state => state.register.Region,
        Key:state => state.register.Key,
        StorageClass:state => state.register.StorageClass
      })
    }
}
</script>

<style lang="scss" scoped>
@import '../assets/css/info.scss';
</style>

